<?php

namespace app\common;

use app\BaseController;

use app\Request;
use think\Exception;
use think\facade\Log;
use think\response\Json;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;
use WeChatPay\Util\PemUtil;
use Yansongda\Supports\Collection;

class Pay extends BaseController
{
	/**
	 * 支付
	 * @param $pay_type *支付类型:1=微信,2=支付宝
	 * @param  $pay_amount
	 * @param  $order_sn
	 * @param $mark
	 * @param $attach
	 * @return array|string
	 * @throws Exception
	 */
	public static function pay($pay_type, $pay_amount, $order_sn, $mark, $attach,$openid='')
	{
		$region = request()->header('region');
		$client = request()->header('client');#app wechat_mini

		
		if (!in_array($region, [0, 1])) {
			throw new Exception('请求错误');
		}
		switch ($pay_type) {
			case 1:
				if ($region == 0) {
					$config = config('pay');
					if ($client == 'wechat_mini'){
						$ret = \Yansongda\Pay\Pay::wechat($config)->mini([
							'out_trade_no' => $order_sn,
							'description' => $mark,
							'amount' => [
								'total' => (int)bcmul($pay_amount, 100),
							],
							'payer' => [
								'openid' => $openid,
							],
							'attach' => $attach
						]);
					}else{
						$ret = \Yansongda\Pay\Pay::wechat($config)->app([
							'out_trade_no' => $order_sn,
							'description' => $mark,
							'amount' => [
								'total' => (int)bcmul($pay_amount, 100),
							],
							'attach' => $attach
						]);
					}
					
				} else {
					$merchantId = '183392298';
					$wx_mchcertificateserial = '3396CB09A4B58FB7678BBEBE0B8C4E9080DA6214';
					$appid = 'wx1ff929a6342755c7';
					// 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
					$merchantPrivateKeyFilePath = file_get_contents('cert/apiclient_key_global.pem');
					$merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
					// 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
					$platformCertificateFilePath = file_get_contents('cert/633D73FFFDFA22C9CEF8BF35922024A443CCA851.crt');
					$platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
					// 从「微信支付平台证书」中获取「证书序列号」
					$platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
					$instance = Builder::factory([
						'mchid' => $merchantId,
						'serial' => $wx_mchcertificateserial,
						'privateKey' => $merchantPrivateKeyInstance,
						'certs' => [
							$platformCertificateSerial => $platformPublicKeyInstance,
						],
					]);
					$resp = $instance->v3->global->transactions->app
						->post(['json' => [
							'mchid' => $merchantId,
							'out_trade_no' => $order_sn,
							'appid' => $appid,
							'trade_type' => 'APP',
							'merchant_category_code' => "4111",
							'description' => $mark,
							'notify_url' => request()->domain() . '/Callback/Notify/paytype/wechat/scene/global',
							'amount' => [
								'total' => (int)bcmul($pay_amount, 100),
								'currency' => 'CNY'
							],
							'attach' => $attach
						]]);
					$resp = json_decode($resp->getBody()->getContents());
					$timestamp = (string)Formatter::timestamp();
					$noncestr = Formatter::nonce();
					$params = [
						'appId' => $appid,
						'timeStamp' => $timestamp,
						'nonceStr' => $noncestr,
						'prepayid' => $resp->prepay_id,
					];
					$ret = [
						'appid' => $appid,
						'partnerid' => $merchantId,
						'prepayid' => $resp->prepay_id,
						'package' => 'Sign=WXPay',
						'noncestr' => $noncestr,
						'timestamp' => $timestamp,
						'sign' => Rsa::sign(Formatter::joinedByLineFeed(...array_values($params)), $merchantPrivateKeyInstance),
					];
				}
				break;
			case 2:
				if ($region == 0) {
					$config = config('pay');
					$ret = \Yansongda\Pay\Pay::alipay($config)->app([
						'out_trade_no' => $order_sn,
						'total_amount' => $pay_amount,
						'subject' => $mark,
						'passback_params' => urlencode($attach)
					])->getBody()->getContents();
				} else {
					throw new Exception('暂未开通支付宝国际支付');
				}
				break;
			default:
				throw new Exception('支付类型错误');
			
		}
		return $ret;
	}
}